<template>
  <div class="wrap">

    <template v-if="scene === 'reset'">

      <template v-if="step === 1">
        <div class="form-box">
          <div class="title">{{ $t('account.passwordModify') }}</div>
          <div class="label">
            <el-input :placeholder="$t('account.inputPwd')" v-model="currentForm.password" show-password @keyup.enter.native="next"></el-input>
          </div>
          <div class="tips">
            <el-link :underline="false" @click="jumpForgetPassword">{{ $t('account.forgetPwd') }}</el-link>
          </div>
          <div class="footer">
            <el-button style="width: 100%;" type="primary" @click="next" :loading="buttonLoading">{{ $t('common.next') }}</el-button>
          </div>
        </div>
      </template>

      <template v-if="step === 2">
        <div class="form-box">
          <div class="title">{{ $t('account.passwordModify') }}</div>
          <el-form ref="resetPassword" :model="resetForm" :rules="resetRules" class="login-form" auto-complete="off" label-position="left">
            <el-form-item class="label" prop="password">
              <el-input :placeholder="$t('account.inputNewPwd')" v-model="resetForm.password" show-password></el-input>
            </el-form-item>
            <el-form-item class="label" prop="rePassword">
              <el-input :placeholder="$t('account.inputNewPwd2')" v-model="resetForm.rePassword" show-password></el-input>
            </el-form-item>

          </el-form>

          <div class="footer">
            <el-button style="width: 100%;" type="primary" @click="resetPassword" :loading="buttonLoading">{{$t('common.confirmModification')}}</el-button>
          </div>
        </div>
      </template>

      <template v-if="step === 3">
        <div class="success-password">
          <div class="title">{{$t('account.passwordModifySuccess')}}</div>
          <div class="img">
            <img src="~@/assets/images/success-password.png" alt="" width="500">
          </div>
          <div class="tips">{{$t('account.after5sLogin')}}</div>
          <div class="goLogin">
            <el-button style="width: 450px" type="primary" @click="goLogin">{{$t('account.loginAgain')}}</el-button>
          </div>
        </div>
      </template>

    </template>

    <template v-if="scene === 'forget'">
      <template v-if="step === 1">
        <div class="form-box">
          <div class="title">{{ $t('account.passwordRetrieval') }}</div>
          <el-form ref="forgetForm" :model="forgetForm" :rules="forgetRules" auto-complete="on" label-position="left">
            <el-form-item class="label" prop="email">
              <el-input :placeholder="$t('account.inputEmail')" v-model="forgetForm.email" name="email"></el-input>
            </el-form-item>

            <el-form-item class="label captcha" prop="captcha">
              <el-input :placeholder="$t('account.inputCode')" v-model="forgetForm.captcha" auto-complete="off">
                <template slot="append"><img :src="captchaSrc" class="captcha-img" alt="" @click="getCaptcha"></template>
              </el-input>
            </el-form-item>

            <el-form-item class="label email-code-label" prop="code">
              <el-input
                ref="code"
                v-model="forgetForm.code"
                :placeholder="$t('account.code')"
                name="code"
                tabindex="2"
                auto-complete="off"
              ></el-input>
              <span class="email-code">
                <el-button
                  size="small"
                  type="primary"
                  @click="sendCode"
                  :disabled="codeLoading"
                >{{btnText}}</el-button>
              </span>
            </el-form-item>

            <div class="label captcha">

            </div>

          </el-form>

          <div class="footer">
            <el-row :gutter="12">
              <el-col :span="8">
                <el-button style="width: 100%;" type="info" @click="goBack">{{ $t('common.prev') }}</el-button>
              </el-col>
              <el-col :span="16">
                <el-button style="width: 100%;" type="primary" @click="checkForget" :loading="buttonLoading">{{ $t('common.next') }}</el-button>
              </el-col>

            </el-row>

          </div>
        </div>
      </template>

      <template v-if="step === 2">
        <div class="form-box">
          <div class="title">{{ $t('account.passwordRetrieval') }}</div>
          <el-form ref="resetPassword" :model="resetForm" :rules="resetRules" class="login-form" auto-complete="off" label-position="left">
            <el-form-item class="label" prop="password">
              <el-input :placeholder="$t('account.inputPwd')" v-model="resetForm.password" show-password></el-input>
            </el-form-item>
            <el-form-item class="label" prop="rePassword">
              <el-input :placeholder="$t('account.inputNewPwd')" v-model="resetForm.rePassword" show-password></el-input>
            </el-form-item>

          </el-form>

          <div class="footer">
            <el-row :gutter="12">
              <el-col :span="8">
                <el-button style="width: 100%;" type="info" @click="goBack">{{ $t('common.prev') }}</el-button>
              </el-col>
              <el-col :span="16">
                <el-button style="width: 100%;" type="primary" @click="resetPassword" :loading="buttonLoading">{{ $t('common.confirmModification') }}</el-button>
              </el-col>

            </el-row>

          </div>
        </div>
      </template>

      <template v-if="step === 3">
        <div class="success-password">
          <div class="title">{{$t('account.passwordResetSuccess')}}</div>
          <div class="img">
            <img src="~@/assets/images/success-password.png" alt="" width="500">
          </div>
          <div class="tips">{{$t('account.after5sLogin')}}</div>
          <div class="goLogin">
            <el-button style="width: 450px" type="primary" @click="goLogin">{{$t('account.loginAgain')}}</el-button>
          </div>
        </div>
      </template>
    </template>


  </div>
</template>

<script>
import request from "@/utils/request";
import {checkForgetPassword, checkPassword, resetPassword, sendEmailCode} from "@/api/user";
import {removeToken} from "@/utils/auth";
import {resetRouter} from "@/router";
import {deepCopy, isEmail} from "@/utils";

export default {
  name: "resetPassword",
  data(){
    const validateRePassword = (rule,value,callback) => {
      if (value !== this.resetForm.password) {
        callback(new Error(this.$t('account.pwdNotSame')))
      } else {
        callback()
      }
    }

    const validateEmail = (rule,value,callback) => {
      if (!isEmail(value)) {
        callback(new Error(this.$t('account.invalidEmail')))
      } else {
        callback()
      }
    }

    return {
      scene: 'reset',
      step: 1,
      userId: '',
      currentForm:{
        password: '',
      },
      buttonLoading: false,
      resetForm: {
        password: '',
        rePassword: '',
      },
      resetRules:{
        password:[
          {required:true, message:this.$t('account.mustPwd'),trigger:'blur'},
          {min:6, message:this.$t('account.pwdValid1'),trigger:'blur'},
        ],
        rePassword:[
          {required:true, message:this.$t('account.mustPwd2'),trigger:'blur'},
          {validator:validateRePassword ,trigger: 'blur' }, // 校验手机号格式
        ],
      },
      forgetForm: {
        email: '',
        captcha: '', // 图形验证码
        code: '', // 手机验证码
      },
      captchaSrc: '',
      btnText: this.$t('account.code'),
      forgetRules: {
        email:[
          { required: true, validator:validateEmail, trigger: 'blur' }
        ],
        code: [
          { required: true,message: this.$t('account.mustEmailCode')  ,trigger: 'blur' },
        ],
        captcha: [
          { required: true,message: this.$t('account.inputCode')  ,trigger: 'blur' },
        ],
      },
      codeLoading: false,
    }
  },
  created() {
    this.userId = this.$store.getters.id;
  },
  methods:{
    // 忘记密码 跳转到忘记密码页面
    jumpForgetPassword(){
      this.scene = 'forget';
      this.step = 1;
      this.getCaptcha()
    },
    // 下一步
    next(){
      if(!this.currentForm.password){
        this.$errorMessage(this.$t('account.mustPwd'));
        return;
      }
      this.buttonLoading = true
      const postData = {
        password: this.currentForm.password,
        scene: this.scene,
      }
      checkPassword(postData)
        .then(res=>{
          this.buttonLoading = false;
          if(res.error !== 0){
            this.$errorMessage(res.message)
            return;
          }
          this.step++

        })
    },
    // 重置密码
    resetPassword(){
      this.$refs.resetPassword.validate(valid =>{
        if(valid){
          const postData = {
            password: this.resetForm.password,
            rePassword: this.resetForm.rePassword,
            scene: this.scene,
          }
          this.buttonLoading = true;
          resetPassword(postData)
            .then(res=>{
              this.buttonLoading = false;
              if(res.error === 0){
                this.$successMessage(res.message)
                // 成功
                this.step++
                setTimeout(()=>{
                  this.goLogin()
                },5000)
              }else{
                this.$errorMessage(res.message)
              }

            })
        }
      })
    },
    // 跳转到登录页
    async goLogin() {
      // 清除token
      removeToken()
      resetRouter()
      this.$router.push({
        path: '/login'
      })
    },
    // 获取图形验证码
    getCaptcha(){
      this.captchaSrc = process.env.VUE_APP_BASE_API + '/captcha?id=' + this.userId + '&' + Math.random()
    },
    // 邮箱验证码
    sendCode(){
      if(!isEmail(this.forgetForm.email)){
        this.$errorMessage(this.$t('account.invalidEmail'))
        return;
      }
      this.$refs.code.focus()
      this.codeLoading = true
      this.btnText = this.$t('account.pleaseWait')
      // 发送请求
      sendEmailCode(this.forgetForm.email)
        .then(res=>{
          if(res.error === 0){
            this.doLoop();
            this.$successMessage(this.$t('account.codeSend'));
          }else{
            this.codeLoading = false;
            this.$errorMessage(res.message);
            this.btnText = this.$t('account.code')
          }
        })
    },
    // 倒数验证码
    doLoop(seconds = 60){
      this.btnText = seconds ;
      let countDown = setInterval(()=>{
        if(seconds > 0){
          this.btnText = seconds ;
          seconds--;
        }else{
          this.btnText = this.$t('account.code');
          this.codeLoading = false;
          clearInterval(countDown);
        }
      },1000)
    },
    // 校验
    checkForget(){
      this.$refs.forgetForm.validate(valid=>{
        if(valid){
          const postData = deepCopy(this.forgetForm)
          postData.scene = this.scene
          this.buttonLoading = true
          checkForgetPassword(postData)
            .then(res=>{
              this.buttonLoading = false;
              if(res.error === 0){
                this.step++;
              }else{
                this.$errorMessage(res.message)
              }
            })
        }
      })
    },
    goBack(){
      this.step--
      if(this.step === 0){
        this.step = 1;
        this.scene = 'reset'
      }
    }
  }
}
</script>

<style scoped lang="scss">
.wrap{
  padding: 30px 30px;
  .form-box{
    width: 420px;
    max-width: 100%;
    min-height: 250px;
    background-color: #ffffff;
    padding: 50px 30px 30px 30px;
    //padding: 160px 35px 0;
    margin: 50px auto;
    overflow: hidden;
    border-radius: 5px;
    border: 1px solid #d7d7d7;
    .title{
      text-align: center;
      font-weight: 700;
      margin-bottom: 30px;
    }
    .tips{
      display: flex;
      flex-direction: row-reverse;
    }
    .footer{
      margin-top: 20px;
    }
    //box-shadow:darkgrey 10px 10px 30px 5px;
    .success-password{
      margin-top: 50px;
      display: flex;
      text-align: center;
      flex-direction: column;
      .title{
        font-size: 16px;
        font-weight: 650;
        font-style: normal;
        color: #4c91c6;
      }
      .tips{
        font-weight: 400;
        font-style: normal;
        font-size: 16px;
        margin: 20px 0;
      }
    }
  }
  .captcha-img{
    cursor: pointer;
    height: 25px;
  }
  .success-password{
    margin-top: 50px;
    display: flex;
    text-align: center;
    flex-direction: column;
    .title{
      font-size: 16px;
      font-weight: 650;
      font-style: normal;
      color: #4c91c6;
    }
    .tips{
      font-weight: 400;
      font-style: normal;
      font-size: 16px;
      margin: 20px 0;
    }
  }
  .email-code-label{
    position: relative;
    .email-code {
      position: absolute;
      right: 0;
      top: -2px;
      font-size: 16px;
      cursor: pointer;
      user-select: none;
    }
  }
}
</style>
